package bb.lanxing.util.jsbridge;

import android.os.Build;
import android.os.Looper;
import android.os.SystemClock;
import android.text.TextUtils;
import android.webkit.ValueCallback;
import androidx.collection.ArrayMap;
import com.google.gson.Gson;
import bb.lanxing.util.jsbridge.WebViewClientProxy;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class BridgeHelper implements WebViewJavascriptBridge, WebViewClientProxy.OnLoadJSListener {
    private IWebView webView;
    private Map<String, BridgeHandler> mMessageHandlers = new ArrayMap();
    private Map<String, CallBackFunction> mCallbacks = new ArrayMap();
    private BridgeHandler mDefaultHandler = new DefaultHandler();
    private List<Object> mMessages = new ArrayList();
    private long mUniqueId = 0;
    private boolean mJSLoaded = false;
    private Gson mGson = new Gson();

    public BridgeHelper(IWebView webView) {
        this.webView = webView;
        webView.addJavascriptInterface(new BaseJavascriptInterface(this), "android");
        webView.setWebViewClient(new BridgeWebViewClient() {
//            {
//                BridgeHelper.this = this;
//            }

            @Override
            public void onBridgeLoadStart() {
                BridgeHelper.this.mJSLoaded = false;
            }

            @Override
            public void onBridgeLoadFinished() {
                BridgeHelper.this.mJSLoaded = true;
                if (BridgeHelper.this.mMessages != null) {
                    for (Object obj : BridgeHelper.this.mMessages) {
                        BridgeHelper.this.dispatchMessage(obj);
                    }
                    BridgeHelper.this.mMessages = null;
                }
            }
        });
    }

    public void setGson(Gson gson) {
        this.mGson = gson;
    }

    public boolean isJSLoaded() {
        return this.mJSLoaded;
    }

    public final Map<String, CallBackFunction> getResponseCallbacks() {
        return this.mCallbacks;
    }

    public final Map<String, BridgeHandler> getMessageHandlers() {
        return this.mMessageHandlers;
    }

    public final BridgeHandler getDefaultHandler() {
        return this.mDefaultHandler;
    }

    @Override
    public void onLoadStart() {
        this.mJSLoaded = false;
    }

    @Override
    public void onLoadFinished() {
        this.mJSLoaded = true;
        List<Object> list = this.mMessages;
        if (list != null) {
            for (Object obj : list) {
                dispatchMessage(obj);
            }
            this.mMessages = null;
        }
    }

    @Override
    public void sendToWeb(Object data) {
        sendToWeb(data, (CallBackFunction) null);
    }

    @Override
    public void sendToWeb(Object data, CallBackFunction responseCallback) {
        doSend(null, data, responseCallback);
    }

    public void callHandler(String handlerName, String data, CallBackFunction callBack) {
        doSend(handlerName, data, callBack);
    }

    @Deprecated
    public void setDefaultHandler(BridgeHandler handler) {
        this.mDefaultHandler = handler;
    }

    @Deprecated
    public void registerHandler(String handlerName, BridgeHandler handler) {
        if (handler != null) {
            this.mMessageHandlers.put(handlerName, handler);
        }
    }

    @Deprecated
    public void unregisterHandler(String handlerName) {
        if (handlerName != null) {
            this.mMessageHandlers.remove(handlerName);
        }
    }

    @Override
    public void sendToWeb(String function, Object... values) {
        if (Thread.currentThread() == Looper.getMainLooper().getThread()) {
            String format = String.format(BridgeUtil.JAVASCRIPT_STR, String.format(function, values));
            if (Build.VERSION.SDK_INT >= 19) {
                this.webView.evaluateJavascript(format, null);
            } else {
                this.webView.loadUrl(format);
            }
        }
    }

    @Override
    public void sendToWeb(String function, ValueCallback<String> callback, Object... values) {
        if (Thread.currentThread() == Looper.getMainLooper().getThread()) {
            this.webView.evaluateJavascript(String.format(BridgeUtil.JAVASCRIPT_STR, String.format(function, values)), callback);
        }
    }

    private void doSend(String handlerName, Object data, CallBackFunction responseCallback) {
        boolean z = data instanceof String;
        if (z || this.mGson != null) {
            JSRequest jSRequest = new JSRequest();
            if (data != null) {
                jSRequest.data = z ? (String) data : this.mGson.toJson(data);
            }
            if (responseCallback != null) {
                StringBuilder sb = new StringBuilder();
                long j = this.mUniqueId + 1;
                this.mUniqueId = j;
                sb.append(j);
                sb.append("_");
                sb.append(SystemClock.currentThreadTimeMillis());
                String format = String.format(BridgeUtil.CALLBACK_ID_FORMAT, sb.toString());
                this.mCallbacks.put(format, responseCallback);
                jSRequest.callbackId = format;
            }
            if (!TextUtils.isEmpty(handlerName)) {
                jSRequest.handlerName = handlerName;
            }
            queueMessage(jSRequest);
        }
    }

    private void queueMessage(Object message) {
        List<Object> list = this.mMessages;
        if (list != null) {
            list.add(message);
        } else {
            dispatchMessage(message);
        }
    }

    public void dispatchMessage(Object message) {
        Gson gson = this.mGson;
        if (gson == null) {
            return;
        }
        String format = String.format(BridgeUtil.JS_HANDLE_MESSAGE_FROM_JAVA, gson.toJson(message).replaceAll("(\\\\)([^utrn])", "\\\\\\\\$1$2").replaceAll("(?<=[^\\\\])(\")", "\\\\\"").replaceAll("(?<=[^\\\\])(')", "\\\\'").replaceAll("%7B", URLEncoder.encode("%7B")).replaceAll("%7D", URLEncoder.encode("%7D")).replaceAll("%22", URLEncoder.encode("%22")));
        if (Thread.currentThread() == Looper.getMainLooper().getThread()) {
            if (Build.VERSION.SDK_INT >= 19) {
                this.webView.evaluateJavascript(format, null);
            } else {
                this.webView.loadUrl(format);
            }
        }
    }

    public void sendResponse(Object data, String callbackId) {
        boolean z = data instanceof String;
        if ((z || this.mGson != null) && !TextUtils.isEmpty(callbackId)) {
            final JSResponse jSResponse = new JSResponse();
            jSResponse.responseId = callbackId;
            jSResponse.responseData = z ? (String) data : this.mGson.toJson(data);
            if (Thread.currentThread() == Looper.getMainLooper().getThread()) {
                dispatchMessage(jSResponse);
            } else {
                this.webView.post(new Runnable() {
//                    {
//                        BridgeHelper.this = this;
//                    }

                    @Override
                    public void run() {
                        BridgeHelper.this.dispatchMessage(jSResponse);
                    }
                });
            }
        }
    }

    public void destroy() {
        this.mCallbacks.clear();
        this.mMessageHandlers.clear();
    }
}
